import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'index.dart';
import 'widgets/index.dart';
import '../home_hot/index.dart';
import '../home_follow/index.dart';
import '../home_mall/index.dart';

class HomeIndexPage extends GetView<HomeIndexController> {
  const HomeIndexPage({super.key});

  // 主视图 - 根据顶部Tab显示不同内容
  Widget _buildView() {
    return Obx(() {
      // 根据当前选中的tab显示不同页面
      switch (controller.currentTopTabIndex.value) {
        case 0: // 推荐
          return _buildRecommendView();
        case 1: // 热播
          return const HomeHotPage();
        case 2: // 关注
          return const HomeFollowPage();
        case 3: // 商城
          return const HomeMallPage();
        default:
          return _buildRecommendView();
      }
    });
  }

  // 推荐页面视图（原来的视频列表）
  Widget _buildRecommendView() {
    return Obx(() {
      // 如果视频列表还没初始化，显示加载页面
      if (controller.videoList.isEmpty) {
        return Container(
          color: Colors.black,
          child: const Center(
            child: CircularProgressIndicator(
              color: Colors.white,
            ),
          ),
        );
      }
      
      return PageView.builder(
        controller: controller.pageController,
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        onPageChanged: controller.onPageChanged,
        itemCount: controller.videoList.length,
        itemBuilder: (context, index) {
          return _buildVideoPage(index);
        },
      );
    });
  }

  // 构建单个视频页面
  Widget _buildVideoPage(int index) {
    final video = controller.videoList[index];
    return Obx(() {
      // 判断是否应该播放：
      // 1. 是当前页面
      // 2. 视频播放状态为true（受生命周期控制）
      // 3. 在推荐Tab页面（index 0）
      final isCurrentPage = controller.currentPlayingIndex.value == index;
      final isInRecommendTab = controller.currentTopTabIndex.value == 0;
      final shouldPlay = isCurrentPage && 
                        controller.isVideoPlaying.value && 
                        controller.isPageVisible.value &&
                        isInRecommendTab;
      
      return Stack(
        children: [
          // 视频播放器
          VideoPlayerWidget(
            videoUrl: video.videoUrl,
            coverImage: video.coverImage,
            isPlaying: shouldPlay,
            onTap: () => controller.onVideoTap(index),
          ),
          
          // 视频信息覆盖层
          VideoInfoOverlay(
            video: video,
            onLikeTap: () => controller.onLikeTap(index),
            onCommentTap: () => controller.onCommentTap(index),
            onShareTap: () => controller.onShareTap(index),
          ),
        ],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeIndexController>(
      init: HomeIndexController(),
      id: "home_index",
      builder: (_) {
        return Scaffold(
          extendBodyBehindAppBar: true, // 让视频延伸到AppBar和状态栏下方
          backgroundColor: Colors.black,
          appBar: _buildAppBar(),
          body: _buildView(),
        );
      },
    );
  }

  // 构建AppBar - 抖音风格（美化版 + 黑色主题）
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      elevation: 0,
      backgroundColor: Colors.transparent,
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light,
        statusBarBrightness: Brightness.dark,
      ),
      title: Obx(() => Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _buildTopTab('推荐', 0),
          SizedBox(width: 25.w),
          _buildTopTab('热播', 1),
          SizedBox(width: 25.w),
          _buildTopTab('关注', 2),
          SizedBox(width: 25.w),
          _buildTopTab('商城', 3),
        ],
      )),
      actions: [
        Container(
          margin: EdgeInsets.only(right: 8.w),
          child: IconButton(
            onPressed: controller.onSearchTap,
            icon: Container(
              padding: EdgeInsets.all(6.r),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.15),
                borderRadius: BorderRadius.circular(10.r),
              ),
              child: Icon(
                Icons.search,
                color: Colors.white,
                size: 22.r,
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建顶部标签（美化版 + 屏幕适配 + 黑色主题）
  Widget _buildTopTab(String text, int index) {
    final isActive = controller.currentTopTabIndex.value == index;
    
    return GestureDetector(
      onTap: () => controller.onTopTabTap(index),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: EdgeInsets.symmetric(
          horizontal: isActive ? 14.w : 10.w,
          vertical: 6.h,
        ),
        decoration: BoxDecoration(
          gradient: isActive
              ? LinearGradient(
                  colors: [
                    Colors.white.withOpacity(0.25),
                    Colors.white.withOpacity(0.1),
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                )
              : null,
          borderRadius: BorderRadius.circular(20.r),
          border: isActive
              ? Border.all(
                  color: Colors.white.withOpacity(0.3),
                  width: 1,
                )
              : null,
        ),
        child: Text(
          text,
          style: TextStyle(
            color: isActive ? Colors.white : Colors.white.withOpacity(0.65),
            fontSize: isActive ? 16.sp : 14.sp,
            fontWeight: isActive ? FontWeight.bold : FontWeight.w500,
            letterSpacing: isActive ? 0.3 : 0,
            shadows: isActive
                ? [
                    Shadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 8.r,
                      offset: Offset(0, 2.h),
                    ),
                  ]
                : [
                    Shadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 4.r,
                      offset: Offset(0, 1.h),
                    ),
                  ],
          ),
        ),
      ),
    );
  }
}
